define(function(require, exports, module) {
	var common = require('./data'), ChinaData = common.data, dropdownlist = Object.create(common.linkInterface);

	dropdownlist.init = function(){
		JSON.Path.tree = ChinaData;
		var _data = JSON.Path.hashSearch(this.selectData); // 各级控件要显示的数据（都是已选中的）

	    this.select(ChinaData, 0);
	    this.select(_data[0].sub, 1);
	    this.select(_data[1].sub, 2);

	    this.selectUIs[2].onchange = this.selectUIs[1].onchange = this.selectUIs[0].onchange = onChange.bind(this);
	}

    dropdownlist.select = function (arr, level) {
    	var selectEl = this.selectUIs[level];

	    selectEl.innerHTML = ""; //删除所有已设置的option
        var selectedValue = 0;
        for(var i = 0, j = arr.length; i < j; i++){

            var locationName = arr[i].name;
            var opt = document.createElement("option");
            
            opt.text = opt.value = locationName;
            if (locationName == "请选择") {
                opt.value = "";
            }

            console.log('locationName:' + locationName)
            console.log('this.selectData[level]:' + this.selectData[level])
            if (locationName == this.selectData[level]) {
// debugger;
                opt.selected = "selected";
                selectedValue = locationName; //输出值
            }
            try {
                selectEl.add(opt, null);
            } catch (e) {
                selectEl.add(opt);
            }
        }

        if(!selectedValue && selectEl.children.length){// 默认第一项显示
        	selectEl.children[0].selected = "selected";
        	selectedValue = selectEl.children[0].value;
        	// throw '未选择任何节点！';
        }

        return selectedValue;
    }
	function onChange(e){
		var _data
			uiIndex = this.selectUIs.indexOf(e.target), // 控件在级联控件的索引
			currentValue = this.selectUIs[uiIndex].value;// 刚才选择的记录

		if(this.levelCount != uiIndex){
			// 最开始的控件
	    	if(uiIndex == 0){
	    		_data = JSON.Path.getNode("/" + currentValue).sub;
	    	}else{
	    		_data = JSON.Path.getNode(this.selectData[uiIndex - 1], currentValue).sub;// 之前的数据
	    	}

	    	this.selectData[uiIndex]	 = currentValue;
	        this.selectData[uiIndex + 1] = this.select(_data, uiIndex + 1); // 下一个控件
		}else if(this.levelCount == uiIndex){
			// 最后一个控件，不联动，仅保存选择项
			this.selectData[this.levelCount] = this.selectUIs[this.levelCount].value;
		}
	}

	module.exports = dropdownlist;
});